package com.auto.learning.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;

import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.auto.learning.MainActivity;
import com.auto.learning.R;
import com.auto.learning.bean.BreakPointBean;
import com.auto.learning.bean.PlayBean;
import com.auto.learning.event.BreakPointTipsEvent;
import com.auto.learning.event.CheckStatusEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.NowPlayEvent;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.SharedPreferencesUtils;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

public class PlayService extends Service implements OnPreparedListener,OnCompletionListener,OnErrorListener,OnAudioFocusChangeListener {
	
	
	private final static String CALL_ACTION = "android.intent.action.PHONE_STATE";
	
	private PhoneStatRec phoneStateRec;
	private boolean isringpause = false;
	
	private LocationManagerProxy mLocationManagerProxy;
	
	private MediaPlayer mediaPlayer;
	
	private ExecutorService pool;
	
	private PlayBean playBean;
	
	private boolean isPlaying;
	private int totalDuration;
	private NowPlayEvent nowPlayEvent;
	
	private AudioManager audioManager;
	
	private Handler handle = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				if (mediaPlayer != null) {
					mediaPlayer.seekTo(msg.arg1);
				}
				break;
			case 2:
				CommonMethod.makeNotice(PlayService.this, getResources().getString(R.string.connect_err_io));
				EventBus.getEventBus("m_play_stute").post(false);
				break;
			}
		};
	};

	@Override
	public void onCreate() {
		super.onCreate();
		init();
		setPool(Executors.newCachedThreadPool());
		audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
		
		phoneStateRec = new PhoneStatRec();// 来电的广播
		IntentFilter mIntentFilter = new IntentFilter();
		mIntentFilter.addAction(CALL_ACTION);
		registerReceiver(phoneStateRec, mIntentFilter);
		
		
		registerEvent();
		mediaPlayer = new MediaPlayer();
//		mediaPlayer.setLooping(true);
		mediaPlayer.setOnCompletionListener(this);
		mediaPlayer.setOnPreparedListener(this);
		mediaPlayer.setOnErrorListener(this);
	}
	
	boolean playStatus = false;    //判读音频开始之前是否在播放
	
	@Override
	public void onAudioFocusChange(int focusChange) {
		if (focusChange != 1) {
			if (mediaPlayer != null && mediaPlayer.isPlaying()) {
				playStatus = true;
				pause();
			}
		} else {
			if (playStatus) {
				playStatus = false;
				pause();
			}
		}
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		showButtonNotify();
		return super.onStartCommand(intent, flags, startId);
	}
	
	private static final String ACTION_BUTTON = "close_notify";
	private final static String INTENT_BUTTONID_TAG = "buttonId";
	
	public void showButtonNotify(){
	     RemoteViews mRemoteViews = new RemoteViews(getPackageName(), R.layout.notify_layout);
	     Intent buttonIntent = new Intent(ACTION_BUTTON); //点击的事件处理
	     buttonIntent.putExtra(INTENT_BUTTONID_TAG, 1);
	     PendingIntent intent_prev = PendingIntent.getBroadcast(this, 1, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
	     mRemoteViews.setOnClickPendingIntent(R.id.image_right, intent_prev);
	     NotificationCompat.Builder mBuilder = new Builder(this);
	     mBuilder.setContent(mRemoteViews).setContentIntent(getDefalutIntent(Notification.FLAG_ONGOING_EVENT)).setWhen(System.currentTimeMillis()).setTicker("路上读书")
         .setPriority(Notification.PRIORITY_DEFAULT).setOngoing(true).setSmallIcon(R.drawable.icon_small);
		 Notification notify = mBuilder.build();
		 notify.flags = Notification.FLAG_ONGOING_EVENT;
	     startForeground(0x111, notify);
	}
	
	public PendingIntent getDefalutIntent(int flags){
		Intent mIntent = new Intent(this, MainActivity.class);
		mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, mIntent, flags);
		return pendingIntent;
	}
	
	
	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		Log.d("onError", what +"  " + extra);
		return false;
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		handle.removeCallbacks(seekBarRun);
		if (playBean.isLast()) {
			SharedPreferencesUtils.setParam(PlayService.this, HttpRequestHelper.CONTINUE_PLAY_BOOKID, 0);
		}
		isPlaying = false;
		EventBus.getEventBus("m_play_stute").post(isPlaying);
		handle.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				EventBus.getEventBus("m_play_next").post(1);				
			}
		}, 500);
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		if (playBean.getSeekTo() > 0) {
			mp.seekTo(playBean.getSeekTo());
			if (!playBean.isContinuePlayPause()) {
				mp.start();
				isPlaying = true;
			}
			EventBus.getEventBus("m_show_break_point_tips").post(new BreakPointTipsEvent());
		} else {
			mp.start();
			isPlaying = true;
		}
		totalDuration = mediaPlayer.getDuration();
		handle.postDelayed(seekBarRun, 1000);
		EventBus.getEventBus("m_play_stute").post(isPlaying);
	}
	
	@Override
	public void onDestroy() {
		stopForeground(true);
		CommonMethod.recordBreakPoint();
		unRegisterEvent();
		if (phoneStateRec != null) {
			unregisterReceiver(phoneStateRec);
		}
		super.onDestroy();
	}
	
	public void play(){
		if (playBean == null || (playBean != null && TextUtils.isEmpty(playBean.getPlayUrl()))) {
			return;
		}
		getPool().execute(new Runnable() {
			
			@Override
			public void run() {
				/*if (mediaPlayer != null) {
					mediaPlayer.reset();
					mediaPlayer.release();
					mediaPlayer = null;
				}
				mediaPlayer = MediaPlayer.create(PlayService.this, Uri.parse(playUrl));
				mediaPlayer.setOnPreparedListener(PlayService.this);
				mediaPlayer.setOnCompletionListener(PlayService.this);
				mediaPlayer.setOnErrorListener(PlayService.this);
				mediaPlayer.start();*/
				try {
					mediaPlayer.reset();
					if(playBean.getPlayUrl().contains("http")) {
						mediaPlayer.setDataSource(PlayService.this, Uri.parse(playBean.getPlayUrl()));
					}else {
						File file = new File(playBean.getPlayUrl());
						FileInputStream inputStream = new FileInputStream(file);
						mediaPlayer.setDataSource(inputStream.getFD());
					}
					mediaPlayer.prepare();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
					handle.sendEmptyMessage(2);
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public void pause(){
		handle.removeCallbacks(seekBarRun);
		handle.postDelayed(seekBarRun, 1000);
		if (mediaPlayer != null) {
			if (mediaPlayer.isPlaying()) {
				mediaPlayer.pause();
				isPlaying = false;
			}else {
				if (mediaPlayer.getCurrentPosition() > 0) {
					mediaPlayer.start();
					isPlaying = true;
				}else {
					play();
				}
			}
			EventBus.getEventBus("m_play_stute").post(isPlaying);
		}
	}
	
	public void stop(){
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
		}
	}
	
	Runnable seekBarRun = new Runnable() {
		@Override
		public void run() {
			if (mediaPlayer != null) {
				int currentDuration = mediaPlayer.getCurrentPosition();
				if (nowPlayEvent ==null) {
					nowPlayEvent = new NowPlayEvent();
				}
				nowPlayEvent.setCurrentPosition(CommonMethod.getNowTime(currentDuration));
				nowPlayEvent.setTotalDuration(CommonMethod.getNowTime(totalDuration));
				nowPlayEvent.setCurrent(currentDuration);
				nowPlayEvent.setTotal(totalDuration);
				SharedPreferencesUtils.setParam(PlayService.this, HttpRequestHelper.CONTINUE_PLAY_BOOK_TIME, currentDuration);
				SharedPreferencesUtils.setParam(PlayService.this, HttpRequestHelper.CONTINUE_PLAY_BOOK_TOTAL_TIME, totalDuration);
				int[] status = MusicPlayManager.getInstance(PlayService.this).isPlayingBookId();
				BreakPointBean breakPointBean = TemporaryVariable.breakPiontMap.get(status[0]);
				if (breakPointBean == null) {
					breakPointBean = new BreakPointBean();
					if (TemporaryVariable.breakPiontMap.size() >= 10) {
						for (Entry<Integer, BreakPointBean> item : TemporaryVariable.breakPiontMap.entrySet()) {
							int key = item.getKey();
							TemporaryVariable.breakPiontMap.remove(key);
							break;
						}
					}
				}
				breakPointBean.setBookId(status[0]);
				breakPointBean.setChapterId(status[1]);
				breakPointBean.setSeekTo(currentDuration);
				TemporaryVariable.breakPiontMap.put(status[0], breakPointBean);
				
				EventBus.getEventBus("m_now_play_time").post(nowPlayEvent);
				handle.postDelayed(seekBarRun, 1000);
			}
		}
	};
	
	@Subscribe
	public void onEventPlay(PlayBean playBean){
		this.playBean = playBean;
		play();
	}
	
	@Subscribe
	public void onEventPause(Boolean pause){
		pause();
	}
	
	@Subscribe
	public void onEventFast(Integer progress){
		handle.obtainMessage(1, progress, 0).sendToTarget();
	}
	
	@Subscribe
	public void onEventChechPlayStatus(CheckStatusEvent checkStatusEvent){
		EventBus.getEventBus("m_play_stute").post(isPlaying);
	}
	
	@Subscribe
	public void onEventPauseOnly(String pauseOnly){
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
			isPlaying = false;
		}
		EventBus.getEventBus("m_play_stute").post(isPlaying);
	}
	
	public void registerEvent(){
		EventBus.getEventBus("m_play" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("m_pause" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("m_pause_only" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("m_fase" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("m_check_play_status" , ThreadEnforcer.MAIN).register(this);
	}
	
	public void unRegisterEvent(){
		EventBus.getEventBus("m_play" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("m_pause" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("m_pause_only" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("m_fase" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("m_check_play_status" , ThreadEnforcer.MAIN).unregister(this);
	}
	
	
	public ExecutorService getPool() {
		return pool;
	}

	public void setPool(ExecutorService pool) {
		this.pool = pool;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	
	
	
	/**
	 * 初始化定位
	 */
	private void init() {
		mLocationManagerProxy = LocationManagerProxy.getInstance(PlayService.this);
		// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// 注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
		// 在定位结束后，在合适的生命周期调用destroy()方法
		// 其中如果间隔时间为-1，则定位只定一次
		mLocationManagerProxy.requestLocationData(LocationProviderProxy.AMapNetwork, 40 * 1000, 15, MusicPlayManager.getInstance(PlayService.this));
		mLocationManagerProxy.setGpsEnable(false);
	}
	
	// 处理来电的时候的暂停
		public class PhoneStatRec extends BroadcastReceiver {
			@Override
			public void onReceive(Context context, Intent intent) {
				TelephonyManager mTelManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
				switch (mTelManager.getCallState()) {
				case TelephonyManager.CALL_STATE_RINGING:// 响铃
					if (mediaPlayer != null && mediaPlayer.isPlaying()) {
						mediaPlayer.pause();
						isringpause = true;
						isPlaying = false;
					}
					EventBus.getEventBus("m_play_stute").post(isPlaying);
					break;
				case TelephonyManager.CALL_STATE_OFFHOOK:// 通话
					if (mediaPlayer != null && mediaPlayer.isPlaying()) {
						mediaPlayer.pause();
						isringpause = true;
						isPlaying = false;
					}
					EventBus.getEventBus("m_play_stute").post(isPlaying);
					break;
				case TelephonyManager.CALL_STATE_IDLE:// 通话结束
					if (mediaPlayer != null && isringpause == true && nowPlayEvent != null) {
						mediaPlayer.start();
						isringpause = false;
						isPlaying = true;
					}
					EventBus.getEventBus("m_play_stute").post(isPlaying);
					break;
				}
			}
		}

}
